package com.cncq.flowable.controller;

import com.cncq.flowable.service.FlowableService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.*;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author yaols
 * date  2022/7/31 00:07
 * version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/flower")
public class FlowerController {

    @Resource
    private FlowableService flowableService;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private ProcessEngine processEngine;

    public Object getTaskCandidateUser(String userId){
        TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateUser(userId);
//        taskService.createTaskQuery().taskcan
        return taskQuery;
    }


    /**
     * 启动流程()
     * @param roleId    角色id（我这里配置候选用户,这里就是用roleId）
     */
    @PostMapping(value = "add")
    public String addExpense(String roleId) {
        //启动流程
        HashMap<String, Object> map = new HashMap<>(4);

        //name="客服代表" flowable:candidateGroups="${customerServiceId}"

        map.put("customerServiceId", roleId);

        //<process id="adviceApply" name="投诉建议" isExecutable="true">
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("adviceApply", map);
        return "提交成功.流程Id为：" + processInstance.getId();
    }

    /**
     * 流转
     *
     * @param processInstanceId 流程id
     */
    @PutMapping(value = "apply")
    public String apply(String processInstanceId,Long userId,boolean isPass) {
        // Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //查询当前办理人的任务ID
        Task task = taskService.createTaskQuery()
                //使用流程实例ID
                .processInstanceId(processInstanceId)
                //任务办理人
                .singleResult();
        if (task == null) {
            throw new RuntimeException("流程不存在");
        }
        //通过审核
        HashMap<String, Object> map = new HashMap<>();
        map.put("taskUser", userId);
        String pass = "NO";
        if(isPass){
            pass = "YES";
        }
        map.put("finishFlag", pass);
        taskService.complete(task.getId(), map);
        return "processed ok!";
    }

    /**
     * 生成流程图
     *
     * @param processId 任务ID
     */
    @GetMapping(value = "processDiagram")
    public void genProcessDiagram(HttpServletResponse httpServletResponse, String processId) throws Exception {
        flowableService.genProcessDiagram(httpServletResponse, processId);
    }

}

